class EventBus {
    constructor() {
        this._listeners_ = {};
    }

    uuid(prefix = '') {
        return `${prefix == '' ? '' : prefix + '_'}${Math.random()
            .toString(36)
            .substr(2)}`;
    }

    on(event, handle) {
        if (typeof this._listeners_[event] == 'undefined') {
            this._listeners_[event] = [];
        }
        const key = this.uuid('evt');
        this._listeners_[event].push({
            key: key,
            handle: handle
        });
        return key;
    }

    // 一次性
    once(event, handle) {
        if (typeof this._listeners_[event] == 'undefined') {
            this._listeners_[event] = [];
        }
        const key = this.uuid('evt_once');
        this._listeners_[event].push({
            key: key,
            handle: handle,
            once: true
        });
        return key;
    }

    emit(event, ...args) {
        const handlers = this._listeners_[event];
        if (Array.isArray(handlers)) {
            this._listeners_[event] = [];
            for (let i = 0; i < handlers.length; i++) {
                const evt = handlers[i];
                evt.handle(...args);
                if (!evt.once) {
                    this._listeners_[event].push(evt);
                }
            }
        }
    }
    // 删除指定订阅
    remove(event, key) {
        if (Array.isArray(this._listeners_[event])) {
            this._listeners_[event] = this._listeners_[event].filter(function (evt) {
                return !(key === evt.key || key === evt.handle);
            });
        }
    }

    hasEvent(event) {
        return event && this._listeners_[event];
    }

    off(event) {
        if (event && this._listeners_[event]) {
            //this._listeners_[event] = null;
            delete this._listeners_[event];
        }
    }

    clean() {
        this._listeners_ = {};
    }
}

export default EventBus;